package com.cjt.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cjt.common.lang.Const;
import com.cjt.common.lang.R;
import com.cjt.pojo.Student;
import com.cjt.pojo.Teacher;
import com.cjt.pojo.User;
import com.cjt.service.UserService;
import com.cjt.utils.ImageUtil;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
@CrossOrigin
public class AuthController extends BaseController {


    @Autowired
    Producer producer;
    @Autowired
    UserService userService;

    @GetMapping("/captcha")
    public R captcha() throws IOException {
        String key = UUID.randomUUID().toString();
        String code = producer.createText();
        code = "aaaa";
        key = "aaaa";
        BufferedImage image = producer.createImage(code);
        String jpg = ImageUtil.encode2Base64Jpg(image);
        redisUtil.hset(Const.CAPTCHA_KEY, key, code, 120);
        return R.success(MapUtil.builder()
                .put("key", key)
                .put("img", jpg)
                .build());
    }


//    @PreAuthorize("hasRole('teacher')")
    @GetMapping("/getname")
    public R getname(){
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        String userid = authentication.getName();
        User user = userService.getByUsername(userid);
        if (user.getCode() == 1) {
            //学生
            Student stu = studentService.getOne(new QueryWrapper<Student>().eq("stu_id", userid));
            return R.success(stu);
        } else if (user.getCode() == 2) {
            //老师
            Teacher tea = teacherService.getOne(new QueryWrapper<Teacher>().eq("tea_id", userid));
            return R.success(tea);
        } else if (user.getCode()==3) {
            return R.success(MapUtil.builder()
                    .put("name", user.getUsername())
                    .put("code", user.getCode())
                    .build());
        }
        return null;
    }
}
